define(['jquery'], function($){
	
  var init = function(dom, $sildes, sildesNum, opts, view) {
    var clientSize = view.getClientSize();
    var $handler = dom;
    var $sildes = $sildes;
    var sildesNum = sildesNum;
    var clientWidth = $handler.children()[0].clientWidth;
    var touchPos = {
      startX: '',
      endX: ''
    }
    var canMoveNext = false;
    var canMovePrev = false;
    var i = 1;
    var defaultOpts = {
      moveDistance: 60,
      interval: 2000,
      auto: false
    };
    var autoSlide;

    var transformFunc = function(dom, pos_X, isAnimate) {
      var defaults = {
        '-webkit-transform': 'translate3d(' + pos_X + 'px, 0, 0)',
        'transform': 'translate3d(' + pos_X + 'px, 0, 0)',
        '-webkit-transition': '-webkit-transform 0s',
        'transition': 'transform 0s'
      }
      if (isAnimate) {
        $.extend(defaults, {
          '-webkit-transition': '-webkit-transform .3s',
          'transition': 'transform .3s'
        })
      }
      dom.css(defaults);
      if (i > 0 && i < sildesNum - 1) activeItem(i)
    }

    var auto = function() {
      i = i < sildesNum - 1 ? ++i : 0;
      transformFunc($handler, -i * clientWidth, true);
      if (i > sildesNum - 2) {
        i = 1;
        setTimeout(function(){
          transformFunc($handler, -i * clientWidth, false);
        }, 300)
      }
    }

    var activeItem = function(i) {
      $handler.find('.active').removeClass('active');
      $($sildes[i]).addClass('active');
    }

    _.extend(defaultOpts, opts);

    transformFunc($handler, -1 * clientWidth, false);
    if (defaultOpts.auto) autoSlide = setInterval(auto, defaultOpts.interval);

		$handler.on('touchstart', function(e) {
	    touchPos.startX = e.originalEvent.touches[0].pageX;
	    clearInterval(autoSlide);
	  });
	  $handler.on('touchmove', function(e) {
	    touchPos.endX = e.originalEvent.touches[0].pageX;
	    var deltaX = touchPos.endX - touchPos.startX;
	    canMoveNext = deltaX < -defaultOpts.moveDistance ? true : false;
	    canMovePrev = deltaX > defaultOpts.moveDistance ? true : false;
	    transformFunc($handler, deltaX - i * clientWidth, true);
	  });
	  $handler.on('touchend', function(e) {
	    i = (canMoveNext && i < sildesNum - 1) ? ++i : (canMovePrev && i > 0) ? --i : i;
	    transformFunc($handler, -i * clientWidth, true);
	    if (defaultOpts.auto) autoSlide = setInterval(auto, defaultOpts.interval);
      if (i < 1 || i > sildesNum - 2) {
        i = i < 1 ? sildesNum - 2 : (i > sildesNum - 2) ? 1 : i;
        setTimeout(function() {
          transformFunc($handler, -i * clientWidth, false);
        }, 300);
      }
	  });  	

    
  }

  return {
    init: function(dom, opts, view){
      var $handler = dom;
      var $sildes = $handler.children();
      var sildesNum = $sildes.length;
      // $($sildes[sildesNum - 3]).children('img').on('load', function() {
        init(dom, $sildes, sildesNum, opts, view)  
      // })
      
    }
  }
})